package com.rwdesign.springboot.Waimai.controller;

import com.rwdesign.springboot.Waimai.entity.Goods;
import com.rwdesign.springboot.Waimai.entity.Order;
import com.rwdesign.springboot.Waimai.service.GoodsService;
import com.rwdesign.springboot.Waimai.service.OrderService;
import com.rwdesign.springboot.Waimai.service.UserService;
import com.rwdesign.springboot.Waimai.utils.ResultBody;
import com.rwdesign.springboot.Waimai.vo.AddGoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author cdp
 * @create 2022-01-29 13:06
 */


@CrossOrigin
@RestController
@RequestMapping("/waimai/sys")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @Autowired
    private GoodsService goodsService;

    public boolean isLogin(String userToken) {
        if (userToken == null) {
            return false;
        } else if (userService.selectIdByToken(userToken) != null) {
            return true;
        } else {
            return false;
        }
    }

    // 查询是否为商户
    public boolean isShoper(String userToken) {
        if (userToken == null) {
            return false;
        } else if ("1".equals(userService.selectIsShoperByUserId(userService.selectIdByToken(userToken)))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @return
     * @Author chendanping
     * @Description //TODO 查询所有订单
     * @Date 20:59 2022/3/1
     * @Param
     **/
    @RequestMapping(value = "/getAllOrders", method = RequestMethod.POST)
    public ResultBody getAllOrders(@RequestBody(required = false) Map<String, String> requestInfo, HttpServletRequest request) {
        if (!isLogin(request.getHeader("Authorization"))) {
            return ResultBody.isError(402, "Token错误或已过期");
        }
        System.out.println(request.getHeader("Authorization"));

        Integer userId = userService.selectIdByToken(request.getHeader("Authorization"));

        List<Order> list = orderService.selectAllOrders(requestInfo.get("orderStatus"), userId);

        if (list != null) {
            Map data = new HashMap();
            data.put("data", list);
            return ResultBody.isOk(200, "success", data);
        } else {
            return ResultBody.isError(500, "error");
        }

    }

    /**
     * @return
     * @Author chendanping
     * @Description //TODO 查询订单中的商品
     * @Date 20:59 2022/3/1
     * @Param
     **/
    @RequestMapping(value = "/getGoodsByOrder", method = RequestMethod.POST)
    public ResultBody getGoodsByOrder(@RequestBody(required = false) Map<String, String> requestInfo, HttpServletRequest request) {
        if (!isLogin(request.getHeader("Authorization"))) {
            return ResultBody.isError(402, "Token错误或已过期");
        }
        System.out.println(request.getHeader("Authorization"));

        System.out.println(requestInfo);

        Map data = new HashMap();

        String[] goodsIdArray = null;
        goodsIdArray = requestInfo.get("goodsId").split(",");
        List<Object> goodslist = new ArrayList<>();
        for (int j = 0; j < goodsIdArray.length; j++) {
            Goods goods = goodsService.selectGoodsById(Integer.parseInt(goodsIdArray[j]));
            goodslist.add(goods);
        }
        data.put("orderId", requestInfo.get("orderId"));
        data.put("goodsList", goodslist);
        return ResultBody.isOk(200, "success", data);


    }

    /**
     * @return
     * @Author chendanping
     * @Description //TODO 生成订单
     * @Date 20:59 2022/3/1
     * @Param
     **/
    @RequestMapping(value = "/createOrder", method = RequestMethod.POST)
    public ResultBody createOrder(@RequestBody(required = false) Map<String, String> requestInfo, HttpServletRequest request) {
        if (!isLogin(request.getHeader("Authorization"))) {
            return ResultBody.isError(402, "Token错误或已过期");
        }
        System.out.println(request.getHeader("Authorization"));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Integer userId = userService.selectIdByToken(request.getHeader("Authorization"));
        Order order = new Order();
        order.setOrderId(null);
        order.setOrderStatus("0");
        order.setOrderName(requestInfo.get("orderName"));
        order.setOrderPhone(requestInfo.get("orderPhone"));
        order.setOrderAddress(requestInfo.get("orderAddress"));
        order.setOrderStartTime(df.format(new Date()));
        order.setOrderEndTime("");
        order.setOrderTotalPrice(requestInfo.get("priceTotal"));
        order.setUserId(userId);
        order.setGoodsId(requestInfo.get("goodsId"));
        order.setShopId(Integer.parseInt(requestInfo.get("shopId")));
        int result = orderService.insertOrder(order);

        if (result == 1) {
            Map data = new HashMap();
            return ResultBody.isOk(200, "success", data);
        } else {
            return ResultBody.isError(500, "error");
        }

    }

    //  商户权限---------------------------------------------------------------------------------------------------------------------------------------------------------


    /**
     * @return
     * @Author chendanping
     * @Description //TODO 查询商家的订单
     * @Date 21:25 2022/3/7
     * @Param
     **/
    @RequestMapping(value = "/getShoperOrders", method = RequestMethod.POST)
    public ResultBody getShoperOrders(@RequestBody(required = false) Map<String, String> requestInfo, HttpServletRequest request) {
        System.out.println(request.getHeader("Authorization"));

        if (!isLogin(request.getHeader("Authorization"))) {
            return ResultBody.isError(402, "Token错误或已过期");
        } else if (!isShoper(request.getHeader("Authorization"))) {
            return ResultBody.isError(401, "非商家，身份验证失败");
        } else if (userService.selectShopIdByUserId(userService.selectIdByToken(request.getHeader("Authorization"))) == null) {
            return ResultBody.isError(255, "暂未开店");
        } else {

            List<Order> list = orderService.selectShoperOrdersById(requestInfo.get("orderStatus"), userService.selectShopIdByUserId(userService.selectIdByToken(request.getHeader("Authorization"))));

            if (list != null) {
                Map data = new HashMap();
                data.put("data", list);
                return ResultBody.isOk(200, "success", data);
            } else {
                return ResultBody.isError(500, "error");
            }

        }

    }


    /**
     * @return
     * @Author chendanping
     * @Description //TODO 结束订单
     * @Date 21:25 2022/3/7
     * @Param
     **/
    @RequestMapping(value = "/endOrders", method = RequestMethod.POST)
    public ResultBody endOrders(@RequestBody(required = false) Map<String, String> requestInfo, HttpServletRequest request) {
        System.out.println(request.getHeader("Authorization"));

        if (!isLogin(request.getHeader("Authorization"))) {
            return ResultBody.isError(402, "Token错误或已过期");
        } else if (!isShoper(request.getHeader("Authorization"))) {
            return ResultBody.isError(401, "非商家，身份验证失败");
        } else if (userService.selectShopIdByUserId(userService.selectIdByToken(request.getHeader("Authorization"))) == null) {
            return ResultBody.isError(255, "暂未开店");
        } else {
            String[] ordersIdArray = null;
            ordersIdArray = requestInfo.get("orderIds").split(",");
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            for (int j = 0; j < ordersIdArray.length; j++) {
                if (orderService.updateOrderEndTimeById("1", df.format(new Date()), Integer.parseInt(ordersIdArray[j])) != 1) {
                    return ResultBody.isError(205, "操作失败");
                }
            }
            return ResultBody.isOk(200, "success");

        }

    }

}
